/**
*┌──────────────────────────────────────────────────────────────┐
*│　描    述：服务                                                   
*│　作    者：sys                                              
*│　创建时间：2020-12-02 14:55:26   
*│　说    明：代码生成器生成   
*└──────────────────────────────────────────────────────────────┘
*/
using AutoMapper;
using SXFramWork.Core;
using SXFramWork.Model;
using SXFramWork.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SXFramWork.Service
{
    /// <summary>
	/// SysOrganize服务层
	/// </summary>
    public class SysOrganizeService: ISysOrganizeService
    {
        private readonly ISysOrganizeRepository _repository;
        private readonly IMapper _mapper;

        public SysOrganizeService(ISysOrganizeRepository repository,IMapper mapper)
        {
            _mapper = mapper;
            _repository = repository;
        }

        public async Task<IApiResult> Add(OrgAddModel model)
        {
            var entity = _mapper.Map<SysOrganizeEntity>(model);
            entity.Id = GuidHelper.NewSequentialGuid(SequentialGuidType.SequentialAtEnd);
            entity.CreateTime = DateTime.Now;
            var res= await _repository.InsertAsync(entity);
            if (res.IsNull())
                return ApiResult.NotOk("新增失败");
            return ApiResult.Ok(res);
        }

        public async Task<IApiResult> Delete(string id)
        {
            //删除自己以及下级部门
            var ids = await _repository.GetChildren(id);
            var res= await _repository.DeleteManyAsync(ids,"sysorganize");
            if (res <= 0)
                return ApiResult.NotOk("删除失败");
            return ApiResult.Ok();
        }

        public async Task<IApiResult> GetById(string id)
        {
            var res=await _repository.GetById(id);
            return ApiResult.Ok(res);
        }

        public async Task<IApiResult> GetTree()
        {
            var list = await _repository.GetAllAsync();
            var treeList = new List<OrgTreeResModel>();
            foreach (var item in list.Where(m => m.ParentId.IsNull()||m.ParentId=="0").OrderBy(m => m.Sort))
            {
                //获得子级
                var children = RecursionOrganize(list.ToList(), new List<OrgTreeResModel>(), item.Id);
                treeList.Add(new OrgTreeResModel()
                {
                    Id = item.Id,
                    Label = item.Name,
                    Spread = children.Count > 0,
                    Children = children.Count == 0 ? null : children
                });
            }
            return ApiResult.Ok(treeList);
        }

        public async Task<IApiResult> Query(OrgQueryModel model)
        {
            var result = new PageResult<SysOrganizeEntity>
            {
                Rows = await _repository.Query(model),
                TotalCount = model.TotalCount
            };
            return ApiResult.Ok(result);
        }

        public async Task<IApiResult> Update(OrgUpdateModel model)
        {
            var entity = _mapper.Map<SysOrganizeEntity>(model);
            var res=await _repository.UpdateAsync(entity);
            if (!res)
                return ApiResult.NotOk("更新失败");
            return ApiResult.Ok();
        }

        /// <summary>
        /// 递归部门
        /// </summary>
        /// <param name="sourceList">原数据</param>
        /// <param name="list">新集合</param>
        /// <param name="guid">父节点</param>
        /// <returns></returns>
        List<OrgTreeResModel> RecursionOrganize(List<SysOrganizeEntity> sourceList, List<OrgTreeResModel> list, string id)
        {
            foreach (var row in sourceList.Where(m => m.ParentId == id).OrderBy(m => m.Sort))
            {
                var res = RecursionOrganize(sourceList, new List<OrgTreeResModel>(), row.Id);
                list.Add(new OrgTreeResModel()
                {
                    Id = row.Id,
                    Label = row.Name,
                    Spread = res.Count > 0,
                    Children = res.Count > 0 ? res : null
                });
            }
            return list;
        }
    }
}